aboutsummaryrefslogtreecommitdiff
path: root/src/routes/grocery/[id]/+page.server.ts
blob: 3c3967a10fb2db1fada19f160bd2515a5dbe4908 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81

import { error, fail, redirect } from '@sveltejs/kit';
import { db } from '$lib/server/db';
import { groceries, categories } from '$lib/server/db/schema';
import { eq } from 'drizzle-orm';
import {
	loadForGrocery,
	add as addRef,
	deleteReference,
} from '$lib/server/services/references';
import { deleteGrocery } from '$lib/server/services/groceries';
import {
	numericId,
	parseFormString,
	parseOptionalNumber,
} from '$lib/server/services/validation';
import type { Grocery, Reference } from '$lib/server/services/types';
import type { Actions, PageServerLoad } from './$types';

export interface GroceryDetailOutput {
	item: Grocery & { categoryName: string | null };
	references: Reference[];
}

export const load: PageServerLoad = async ({ params }) => {
	const id = numericId(params.id);

	const [item] = await db.select().from(groceries).where(eq(groceries.id, id));
	if (!item) throw error(404, 'Article introuvable');

	const [cat] = item.categoryId
		? await db
				.select()
				.from(categories)
				.where(eq(categories.id, item.categoryId))
		: [null];

	const refs = await loadForGrocery(id);

	return {
		item: {
			...item,
			categoryName: cat?.name ?? null,
		},
		references: refs,
	};
};

export const actions: Actions = {
	add: async ({ request, params }) => {
		const data = await request.formData();
		const groceryId = numericId(params.id);
		const reference = parseFormString(data.get('reference'));
		const price = parseOptionalNumber(data.get('price'));
		const unit = parseFormString(data.get('unit'));
		const qualityScore = parseOptionalNumber(data.get('quality_score'));

		if (!reference) {
			return fail(400, { error: 'La référence est requise' });
		}

		await addRef(groceryId, reference, price, unit, qualityScore);
		return { success: true };
	},

	delete: async ({ request }) => {
		const data = await request.formData();
		try {
			const id = numericId(data.get('id'));
			await deleteReference(id);
		} catch {
			return fail(400, { error: 'ID invalide' });
		}
		return { success: true };
	},

	deleteItem: async ({ params }) => {
		const groceryId = numericId(params.id);
		await deleteGrocery(groceryId);
		throw redirect(303, '/');
	},
};